<?php
class Lib_MediationApi_Main
{
    private static $obj = null;
    public $public_key;//互联网金融纠纷批量化解中心分配给平台的用于数据加密的密钥
    public $appid;//互联网金融纠纷批量化解中心分配给合作平台的平台代号
    public $url;//

    public function __construct($appid,$public_key)
    {
        $this->appid = $appid;
        $this->public_key = $public_key;
    }

    /**
     * 获取单例对象
     * @param string $appid
     * @return class Lib_MediationApi_Main
     */
    public static function getInstance()
    {
        if (is_null(self::$obj)) {
            self::$obj = new Lib_MediationApi_Main();
        }
        return self::$obj;
    }

    /**
     * 发起请求
     */
    public function sendRequest($request_data)
    {
        try {
            $ts = time();
            if (empty($request_data)) {
                throw new Exception("缺失参数!!");
            }
            $url = $this->url;
            //初始化logs
            $log = ' 发起请求';
            $ssid = str_replace('.', '', uniqid('', true));
            $log .= ',ssid==' . $ssid;
            $log .= ',url==' . $url;
            //组合数据发起请求
            $sm4cipher = new Lib_MediationApi_SM4();
            $en = $sm4cipher->setKey(MD5($this->public_key . $ts))->encryptData(json_encode($request_data));
            $requestBody = [
                "appid" => $this->appid,
                "nonce" => self::generateRandomString(),
                "encrypt_data" => $en,
                "timestamp" => $ts,
            ];
            $log .= ' request='.json_encode($request_data);


            $response = Lib_MediationApi_Curl::postjson($url,$requestBody);
            if ($response['error'] !== 200) {
                $res['code'] = 401;
                $res['data'] = [];
                $res['message'] = '连接失败';
                $log .= ',requestBody==' . json_encode($requestBody);
                $log .= ' response='.json_encode($response);
                Func_Log::write("mediationApiCurl", 'REQUEST', 'link error' . $log);
                return $res;
            }
            
            if($response['code'] != 200){
                $log .= ',requestBody==' . json_encode($requestBody);
                $log .= ' response='.json_encode($response);
                Func_Log::write('mediationApiCurl','REQUEST','request error'.$log);
                return $response;
            }
            return $response;
        } catch (Exception $e) {
            Func_Log::write("mediationApiCurl", 'Exception', $e->getMessage());
            return false;
        }

    }

    /**
     * 测试,生成接口返回的 数据格式,模拟返回数据
     * @param $encrypt_data
     * @return array
     */
    public function testResponse($encrypt_data)
    {
        $key = md5($this->public_key . $this->ts);
        $aescipher = new Lib_Aes($key);
        $encrypt_data = json_encode($encrypt_data);
        $en = $aescipher->encrypt($encrypt_data);

        $requestBody = [
            "appid" => $this->appid,
            "nonce" => self::generateRandomString(6),
            "encrypt_data" => $en,
            "timestamp" => $this->ts,
            "version" => "2.0",
        ];
        $sign = Lib_Signs::sign($requestBody);
        $requestBody["sign"] = $sign;
        return $requestBody;
    }


    /**
     * 获取案件债务信息（由金科主动查询，发起请求）
     */
    public function getDebtInfo($contractNo = null)
    {
        $result = ['code' => 200, 'message' => ''];
        try {
            if (empty($contractNo)) {
                throw new Exception('缺少参数');
            }
            $case_info_detail = Module_OrganCase_Cases::getInstance()->getItemById($contractNo, false, 'CONTRACTNO');
            if (!$case_info_detail) {
                throw new Exception('缺少case_info_detail数据');
            }
            $case_info = Module_Mediate_CaseInfo::getInstance()->getItemById($contractNo, false, 'HTMCBH');
//            if (!$case_info) {
//                throw new Exception('缺少case_info数据');
//            }
            $encrypt_data = [
                "api" => "getDebtInfo",
                "body" => [
                    'contractNo' => $contractNo,
                ]
            ];
            $response = $this->sendRequest($encrypt_data, $this->get_debt_info_url);
            if (isset($response['code'])) {
                return $response;
            }
            if ($response['api'] == 'getDebtInfo' && !empty($response['body'])) {
                $debtAmount = isset($response['body']['debtAmount']) ? $response['body']['debtAmount'] : 0;
                //$debtInterest  = isset($response['body']['debtInterest']) ? $response['body']['debtInterest'] : 0;
                $totalDebt = isset($response['body']['totalDebt']) ? $response['body']['totalDebt'] : 0;
                $targetDate = isset($response['body']['targetDate']) ? $response['body']['targetDate'] : '';

                $updata_info = [];
                $updata_info_detail = [];
                if (!empty($debtAmount)) {
                    if ($case_info) {
                        $updata_info['QHBJ'] = $debtAmount;//欠款本金
                    }
                    $updata_info_detail['DEBTAMOUNT'] = $debtAmount;//欠款本金
                }
//            if(!empty($debtInterest)){
//                $updata_info_detail[]=$debtInterest;//欠款利息
//            }
                if (!empty($totalDebt)) {
                    if ($case_info) {
                        $updata_info['QKZE'] = $totalDebt;//欠款总额
                    }
                    $updata_info_detail['DEBTTOTAL'] = $totalDebt;//欠款总额
                }
                if (!empty($targetDate)) {
                    if ($case_info) {
                        $updata_info['QKZJR'] = $targetDate;//暂记日
                    }
                    $updata_info_detail['DEBTTARGETDATE'] = $targetDate;//暂记日
                }
                if (!empty($updata_info_detail)) {
                    $updata_info_detail['update_time']=time();
                    $res = Module_OrganCase_Cases::getInstance()->updateCaseinfo($contractNo, $updata_info, $updata_info_detail);
                    if (!$res) {
                        throw new Exception('更新失败');
                    }
                }
            } else {
                throw new Exception('接口数据返回异常');
            }
            return $result;
        } catch (Exception $e) {
            $result['code'] = 400;
            $result['message'] = $e->getMessage();
            Func_Log::write("pinganpush", 'getDebtInfo,error', json_encode($response));
            return $result;
        }
    }

    /**
     * 获取随机字符串
     * @param int $length
     * @return string
     */
    public static function generateRandomString($length = 6)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    /**
     * 推送案件调解状态（由金科主动推送，发起请求）
     */
    public function pushMediateStatus($encrypt_data)
    {
        $result = ['code' => 200, 'message' => ''];
        try {
            $response = $this->sendRequest($encrypt_data, $this->push_mediate_status_url);
            if (isset($response['code'])) {
                return $response;
            }
            if ($response['api'] == 'pushMediateStatus' && !empty($response['body'])) {

            } else {
                throw new Exception('接口数据返回异常');
            }
        } catch (Exception $e) {
            $result['code'] = 400;
            $result['message'] = $e->getMessage();
            Func_Log::write("pinganpush", 'getDebtInfo,error', json_encode($result));
            return $result;
        }
        return $response;
    }


}